<template>
	<div class="container1">
    	<div class="product_add">
			<h3 class="tit">上海天光禅寺收款单</h3>
			<el-form ref="form" label-width="120px">
				<el-col :span="8">
					<el-form-item label="收据编号">
					    <el-input disabled v-model="receipt.paymentNumber" type="text" placeholder="请输入"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item  label="金额(元)">
					    <el-input  v-model="receipt.money" type="number" placeholder="请输入" @change="moneyChange"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="收款方式">
						<el-cascader :show-all-levels="false" :options="optionsPayMethod"  v-model="payMethod" ></el-cascader>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="收入类型">
						<el-cascader :show-all-levels="false" :options="optionsPayType" v-model="payType" ></el-cascader>
					</el-form-item>
				</el-col>
				<el-col :span="16">
					<el-form-item label="付款人（单位）">
						<el-select
								v-model="receipt.payer"
								filterable
								remote
								allow-create
								placeholder="请输入"
								:remote-method="remoteMethod"
								:loading="loading">
							<el-option
									v-for="item in payerList"
									:key="item"
									:label="item"
									:value="item">
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item  label="电话">
						<el-input  v-model="receipt.phone" type="text" placeholder="请输入"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item label="法会">
						<el-input  v-model="receipt.fahui" type="text" placeholder="请输入"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item  label="牌位号">
						<el-input  v-model="receipt.paiweiNumber" type="text" placeholder="请输入" @change="moneyChange"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item  label="地址">
						<el-input  v-model="receipt.address" type="text" placeholder="请输入" @change="moneyChange"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="24">
					<el-form-item label="法务信息">
					    <el-input v-model="receipt.paymentFor" type="textarea" :rows="5" placeholder="请输入法务信息"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="经办时间">
						<el-date-picker
								v-model="receipt.handleAt"
								type="date"
								placeholder="选择日期"
						>
						</el-date-picker>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="经办人">
					    <el-input disabled v-model="receipt.handleBy" type="text" placeholder="请输入"></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item>
				    <el-button class="btn_darkBrwon" @click="addReceipt" >新收款单</el-button>
				  </el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item>
				    <el-button class="btn_orange" :disabled="btnSave" @click="save" v-loading="saving">保存</el-button>
				    <el-button class="btn_orange" :disabled="btnPrint"  @click="printBillForQPQ">打印</el-button>
				    <el-button class="btn_lightBrwon" @click="cancel"  >关闭</el-button>
				  </el-form-item>
				</el-col>
       		 </el-form>
    	</div>
	</div>
</template>
<script>
    import ReceiptCodeDao from '@/api/ReceiptCodeDao';
    import ReceiptDao from '@/api/ReceiptDao';
    import Receipt from '@/model/receipt/Receipt';
    import {PayMethod,ReceiptType} from '../../utils/basicData'
    import baseUtil from "../../utils/baseUtil";
    import {createNewWindow} from "../../utils/windowUtil";
    export default {
        name:'Receipt',
        data(){
            return{
                payerList: [],
                loading: false,
                btnSave:false,
                btnPrint:true,
				payMethod:null,
				payType:null,
                receipt:baseUtil.modelCopy(Receipt),
                optionsPayMethod:baseUtil.getOptions(baseUtil.modelCopy(PayMethod)),
                optionsPayType:baseUtil.getOptions(baseUtil.modelCopy(ReceiptType)),
				saving:false,
            }
        },
        methods:{
            unique(arr){
                var x = new Set(arr);
                return [...x];
            },
			remoteMethod(query) {
                if (query !== '' && query != 'null' && query != null  && query != undefined ) {
                    this.loading = true;
                  setTimeout(() => {
                        let paramPayer = this.baseUtil.modelCopy(query);
						let key = eval("/"+paramPayer+"/");
                        let searchParam = {payer: {$regex:key}}
                        let list = []
					    ReceiptDao.findListNoPage(searchParam).then((m)=>{
					        if(this.baseUtil.isNotBlankObj(m) && m.length>0){
								m.forEach((n)=>{ list.push(n.payer) })
								this.payerList = this.unique(list)
                                this.loading = false;
                            }else{
                                this.payerList = []
                                this.loading = false;
                            }
                        })
					}, 200);
                } else {
                    this.payerList = [];
                }
            },
            addReceipt(){
                createNewWindow("#/receipt","收款单",1000,666);
            },
			check(){
                if(!this.baseUtil.isNotBlank(this.receipt.money)) {
                    this.$message({showClose: true,message: '请填写金额',type: 'error'});
                    return false;
                }
                if(!this.baseUtil.isNotBlankObj(this.payMethod)) {
                    this.$message({showClose: true,message: '请选择收款方式',type: 'error'});
                    return false;
                }
                if(!this.baseUtil.isNotBlankObj(this.payType)) {
                    this.$message({showClose: true,message: '请选择收入类型',type: 'error'});
                    return false;
                }
                if(!this.baseUtil.isNotBlank(this.receipt.payer)) {
                    this.$message({showClose: true,message: '请填写付款单位或个人',type: 'error'});
                    return false;
                }
                if(!this.baseUtil.isNotBlankObj(this.receipt.handleAt)) {
                    this.$message({showClose: true,message: '请填写选择经办时间',type: 'error'});
                    return false;
                }
                return true
			},
            save(){
                if(!this.check())return
                let now = new Date();
				let hours = now.getHours()
                let min = now.getMinutes()
                let sec = now.getSeconds()
				let date1 = new Date(this.receipt.handleAt)
                this.receipt.handleAt = new Date(date1.setHours(hours,min,sec))
                this.saving = true
                let method = this.payMethod
				let type = this.payType
                if(this.baseUtil.isNotBlankObj(method) && method.length > 0){
                    this.receipt.payMethod = method[method.length-1]
                }
                if(this.baseUtil.isNotBlankObj(type) && type.length > 0){
                    this.receipt.payType = type[type.length-1]
                }
				let date = new Date(this.receipt.handleAt)
				this.receipt.year  = date.getFullYear()
                this.receipt.month = date.getMonth() + 1
                this.receipt.day = date.getDate()
                ReceiptDao.insertData(this.receipt).then((receiptNew)=>{
                    this.receipt = baseUtil.modelCopy(receiptNew)
                    this.saving = false
                    this.btnSave = true
                    this.btnPrint = false
                    // this.$router.push({name:'receiptList'})
				}).catch(()=>{
                    this.saving = false
				})
			},
            printBillForQPQ() {
                // let bill = this.baseUtil.modelCopy(this.receipt)
                createNewWindow("#/printQPQBill"+"?billId="+this.receipt._id,"打印窗口",1000,666);
            },
            cancel(){
                window.close()
            },
            moneyChange(value){
            	this.receipt.money = this.receipt.money<0? 0 :this.receipt.money
			},
            formatDate(date,format){
                return this.fmUtil.fmDate(date,format)
            },
            prefixInteger(num, length) {
                return (Array(length).join('0') + num).slice(-length);
            },
			async init(){
				this.receipt.handleBy = this.$store.getters.user.username
                this.receipt.type = 'RECEIPT'
				let list = await ReceiptCodeDao.findList({type:'RECEIPT'})
				if(baseUtil.isNotBlankObj(list) && list.length > 0){ //有数据，更新数据
					let receiptCode = list[0];
					let date = receiptCode.dateStr
					let code = receiptCode.code
					if(date == this.formatDate(new Date(),"yyyyMMdd")){ //是今天，继续更新Code，否则，更新日期和Code
						code += 1
						await  ReceiptCodeDao.updateData({_id:receiptCode._id},{code:code})
					}else {
						code = 1
						date = this.formatDate(new Date(),"yyyyMMdd")
						await  ReceiptCodeDao.updateData({_id:receiptCode._id},{dateStr:date,code:code})
					}
					this.receipt.paymentNumber = receiptCode.prefix + date + this.prefixInteger(code ,4)
				}else { //没有数据，插入数据
					await ReceiptCodeDao.insertData({type:'RECEIPT',prefix:'SK',dateStr:this.formatDate(new Date(),"yyyyMMdd"),code:1})
					this.receipt.paymentNumber = 'SK' + this.formatDate(new Date(),"yyyyMMdd") + this.prefixInteger(1 ,4)
				}
            }
        },
        mounted(){
            this.init();
        }
    }
</script>
<style>
</style>
